package com.lcc.gulimall.ware.service.impl;

import com.lcc.common.constant.WareConstant;
import com.lcc.gulimall.ware.entity.PurchaseDetailEntity;
import com.lcc.gulimall.ware.feign.ProductFeignService;
import com.lcc.gulimall.ware.service.PurchaseDetailService;
import com.lcc.gulimall.ware.service.WareSkuService;
import com.lcc.gulimall.ware.vo.DoneVo;
import com.lcc.gulimall.ware.vo.MergeVo;
import com.lcc.gulimall.ware.vo.PurchaseItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcc.common.utils.PageUtils;
import com.lcc.common.utils.Query;

import com.lcc.gulimall.ware.dao.PurchaseDao;
import com.lcc.gulimall.ware.entity.PurchaseEntity;
import com.lcc.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)//status为刚新建和刚分配时可以查到未被接受的采购单
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        //采购单是新建的
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getStatus()); //采购单处于新建状态
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        Long finalPurchaseId = purchaseId;
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> detailEntities = items.stream().map(item -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getStatus());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

    /**
     * 领取采购单
     * @param ids 采购单id
     */
    @Override
    public void received(List<Long> ids) {
        //1.确认当前采购单是新建/已分配状态
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item-> item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getStatus()
                || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getStatus())
                .map(item->{
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getStatus());
                    item.setUpdateTime(new Date());
                    return item;
                }).collect(Collectors.toList());
        //TODO:只能领取自己的采购单
        //2.改变采购单的状态
        this.updateBatchById(purchaseEntities);
        //3.改变采购项的状态
        purchaseEntities.forEach(item->{
            //获取采购单中的采购细节
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailsByPurchaseId(item.getId());
            //更新细节中的状态，属性对拷只保留有用的数据
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getStatus());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);
        });
    }

    @Transactional
    @Override
    public void done(DoneVo doneVo) {

        //2.改变采购项状态
        boolean flag = true;
        List<PurchaseItemVo> items = doneVo.getItems();
        List<PurchaseDetailEntity> updateDetailEntities = new ArrayList<>();
        for(PurchaseItemVo item : items){
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.FAILED.getStatus()){
                flag = false;
            }else{
                //3.将成功采购的进行入库
                //查出采购项的详细信息
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(), purchaseDetailEntity.getWareId(), purchaseDetailEntity.getSkuNum());
            }
            //TODO 重新设计采购单表，添加采购失败原因，以及应采购和实际采购的字段
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            detailEntity.setStatus(item.getStatus());
            updateDetailEntities.add(detailEntity);

        }
        purchaseDetailService.updateBatchById(updateDetailEntities);
        //2.改变采购单状态 => 采购项全部完成则为已完成，采购项有一个采购失败就是有异常
        Long doneVoId = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(doneVoId);
        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED.getStatus());

        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getStatus());
        }
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);


    }

}